package avicit.bdp.dms.dss.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.service.dto.BdpColumnDTO;
import avicit.bdp.common.service.dto.BdpTableDTO;
import avicit.bdp.common.service.dto.CommonTypeDTO;
import avicit.bdp.common.service.service.CommonTypeService;
import avicit.bdp.common.service.service.DataQueryService;
import avicit.bdp.common.service.service.IFileOperate;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.CheckParaUtils;
import avicit.bdp.common.utils.EntityUtils;
import avicit.bdp.common.utils.enums.CommonTypeEnums;
import avicit.bdp.common.utils.enums.StatusEnums;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.core.enums.TableTypeEnum;
import avicit.bdp.core.poi.util.csv.ExportCSVUtil;
import avicit.bdp.core.util.json.JSONUtils;
import avicit.bdp.dms.das.dto.BdpDasCategoryDTO;
import avicit.bdp.dms.das.service.BdpDasCategoryService;
import avicit.bdp.dms.das.service.BdpDasColumnService;
import avicit.bdp.dms.das.service.BdpDasTableService;
import avicit.bdp.dms.dss.dao.DataResourceDAO;
import avicit.bdp.dms.dss.dto.*;
import avicit.bdp.dms.dss.enums.LogRecordCode;
import avicit.bdp.dms.dss.enums.ReleaseType;
import avicit.bdp.dms.dss.enums.ResourceStatus;
import avicit.bdp.dms.dss.enums.ResourceType;
import avicit.bdp.dms.prm.dto.TagDTO;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.SysUserRoleClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.api.sysuser.dto.SysRole;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.properties.PlatformConstant;
import avicit.platform6.core.rest.msg.QueryRespBean;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @金航数码科技有限责任公司
 * @作者：liyb
 * @邮箱：liyb@avic-digital.com
 * @创建时间：2021-03-29 15:21
 * @类说明：数据资源服务
 * @修改记录：
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DataResourceService extends BaseService<DataResourceDAO, DataResourceDTO> {

    @Autowired
    private DataResourceDAO dataResourceDao;
    @Autowired
    private ResourceTagService resourceTagService;
    @Autowired
    private DataQueryService dataQueryService;
    @Autowired
    @Qualifier("hdfsFileOperateService")
    private IFileOperate hdfsFileOperateService;
    @Autowired
    private CommonTypeService commonTypeService;
    @Autowired
    private BdpDasTableService tableService;
    @Autowired
    private BdpDasCategoryService categoryService;
    @Autowired
    private BdpDasColumnService columnService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private DssLogService logService;
    @Autowired
    private ConvertColumnClient convertColumnClient;
    @Autowired
    private DssSubscribeService subscribeService;
    @Autowired
    private SysUserRoleClient sysUserRoleClient;

    /**
     * 查询数据资源列表
     */
    public QueryRespBean<DataResourceDTO> getDataResourceList(String typeId,
                                                              String projectId,
                                                              String name,
                                                              String unSubscribeRes,
                                                              List<Integer> statusList,
                                                              Integer currentPage,
                                                              Integer pageSize) throws Exception {
        List<String> typeIdList = new ArrayList<>();
        if (StringUtils.isNotEmpty(typeId)) {
            commonTypeService.typeIdConvert(typeId, typeIdList, "dataServiceType");
        }

        QueryRespBean<DataResourceDTO> queryRespBean = new QueryRespBean<>();
        // 文档密级
        List<String> wordSecretList = ThreadContextHelper.getWordSecretList();
        com.github.pagehelper.PageHelper.startPage(currentPage, pageSize);

        // 如果是查询未订阅的资源列表
        String currentDescribeUser = null;
        if ("1".equals(unSubscribeRes)) {
            currentDescribeUser = ThreadContextHelper.getUserId();
        }

        Page<DataResourceDTO> dataResourceList = dataResourceDao.getDataResourceList(typeIdList, projectId, name, currentDescribeUser, statusList, wordSecretList);
        valueConvert(dataResourceList);
        queryRespBean.setResult(dataResourceList);
        BdpLogUtil.log4Query(queryRespBean);
        return queryRespBean;
    }

    private void valueConvert(Page<DataResourceDTO> dataResourceList) {
        //循环组装请求数据
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (DataResourceDTO dataResourceDTO : dataResourceList) {
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, dataResourceDTO.getCreatedBy());
            BusinessUtil.createConvertSet(convertFormData, Constants.BDP_DATA_SECRET_LEVEL_KEY, dataResourceDTO.getSecretLevel());
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            //循环设置Alias或Name的值
            for (DataResourceDTO dataResourceDTO : dataResourceList) {
                dataResourceDTO.setReleaseTypeString(ReleaseType.getDescByCode(dataResourceDTO.getReleaseType()));
                dataResourceDTO.setTypeString(ResourceType.getDescByCode(dataResourceDTO.getType()));
                dataResourceDTO.setStatusString(ResourceStatus.getDescByCode(dataResourceDTO.getStatus()));
                dataResourceDTO.setCreatedBy(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER,
                        dataResourceDTO.getCreatedBy()));
                dataResourceDTO.setSecretLevelName(BusinessUtil.convertFormat(
                        convertResultData, Constants.BDP_DATA_SECRET_LEVEL_KEY, dataResourceDTO.getSecretLevel()));
            }
        }
    }

    /**
     * 新增数据资源
     *
     * @param dataResourceDTO 数据资源
     */
    public void insertDataResource(DataResourceDTO dataResourceDTO) {
        logger.info("新增数据资源,参数为{}", JSONObject.toJSONString(dataResourceDTO));

        CheckParaUtils.checkObjectValidity(dataResourceDTO.getReleaseType(), logger, "发布类型必填");
        CheckParaUtils.checkObjectValidity(dataResourceDTO.getType(), logger, "资源类型必填");
        CheckParaUtils.checkStringValidity(dataResourceDTO.getTableId(), logger, "资源选择必填");
        CheckParaUtils.checkStringValidity(dataResourceDTO.getName(), logger, "数据名称必填");
        CheckParaUtils.checkStringValidity(dataResourceDTO.getTypeId(), logger, "数据服务分类必填");

        if (ResourceType.TABLE.getCode() == dataResourceDTO.getType()) {
            List<ColumnInfoDto> columnInfoDtoList = dataResourceDTO.getColumnInfoDtoList();
            if (CollectionUtils.isEmpty(columnInfoDtoList)) {
                throw new BusinessException("返回字段必填");
            }
            dataResourceDTO.setColumnInfo(JSONObject.toJSONString(columnInfoDtoList));

            String tableId = dataResourceDTO.getTableId();
            if (StringUtils.isNotEmpty(dataResourceDTO.getProjectId())) {
                tableId = dataResourceDao.getTableIdByProjectTableId(tableId);
            }
            BdpTableDTO tableDTO = tableService.selectByPrimaryKey(tableId);
            CheckParaUtils.checkDbObjectValidity(tableDTO, logger, String.format("没有查到数据，请确保id:%s的表数据是否存在", tableId));
            dataResourceDTO.setTableName(tableDTO.getName());
        }

        // 校验资源名称唯一性
        checkResName(dataResourceDTO.getName());

        if (ReleaseType.API.getCode() == dataResourceDTO.getReleaseType()) {
            CheckParaUtils.checkStringValidity(dataResourceDTO.getApiAddress(), logger, "API接口地址必填");

            // 校验API接口地址唯一性
            checkApiAddress(dataResourceDTO.getApiAddress());
        }

        // sql过滤校验
        if (dataResourceDTO.getType() == ResourceType.TABLE.getCode()) {
            checkSqlFilter(dataResourceDTO);
        }

        List<OrderInfoDto> orderInfoDtoList = dataResourceDTO.getOrderInfoDtoList();
        if (CollectionUtils.isNotEmpty(orderInfoDtoList)) {
            dataResourceDTO.setOrderInfo(JSONObject.toJSONString(orderInfoDtoList));
        }

        dataResourceDTO.setId(ComUtil.getId());
        dataResourceDTO.setStatus(ResourceStatus.UNPUBLISHED.getCode());
        dataResourceDTO.setDataAuthority(0);
        this.insert(dataResourceDTO);

        // 记录日志
        try {
            BdpLogUtil.log4Insert(dataResourceDTO);
        } catch (Exception e) {
            logger.error("调用平台服务记录日志异常", e);
        }

        // 新增数据资源标签关联信息
        insertResourceTag(dataResourceDTO);
    }

    /**
     * 修改数据资源
     *
     * @param dataResourceDTO 数据资源
     */
    public void updateDataResource(DataResourceDTO dataResourceDTO) {
        logger.info("修改数据资源,参数为{}", JSONObject.toJSONString(dataResourceDTO));

        CheckParaUtils.checkObjectValidity(dataResourceDTO.getReleaseType(), logger, "发布类型必填");
        CheckParaUtils.checkObjectValidity(dataResourceDTO.getType(), logger, "资源类型必填");
        CheckParaUtils.checkStringValidity(dataResourceDTO.getTableId(), logger, "资源选择必填");
        CheckParaUtils.checkStringValidity(dataResourceDTO.getName(), logger, "数据名称必填");
        CheckParaUtils.checkStringValidity(dataResourceDTO.getTypeId(), logger, "数据服务分类必填");

        DataResourceDTO dataResource = this.selectByPrimaryKey(dataResourceDTO.getId());
        CheckParaUtils.checkDbObjectValidity(dataResource, logger, String.format("没有查到数据，请确保id:%s的资源数据是否存在", dataResourceDTO.getId()));

        if (ResourceType.TABLE.getCode() == dataResourceDTO.getType()) {
            List<ColumnInfoDto> columnInfoDtoList = dataResourceDTO.getColumnInfoDtoList();
            if (CollectionUtils.isEmpty(columnInfoDtoList)) {
                throw new BusinessException("返回字段必填");
            }
            dataResourceDTO.setColumnInfo(JSONObject.toJSONString(columnInfoDtoList));

            String tableId = dataResourceDTO.getTableId();
            if (StringUtils.isNotEmpty(dataResource.getProjectId())) {
                tableId = dataResourceDao.getTableIdByProjectTableId(tableId);
            }
            BdpTableDTO tableDTO = tableService.selectByPrimaryKey(tableId);
            CheckParaUtils.checkDbObjectValidity(tableDTO, logger, String.format("没有查到数据，请确保id:%s的表数据是否存在", tableId));
            dataResourceDTO.setTableName(tableDTO.getName());
        }

        // 校验资源名称唯一性
        if (!dataResourceDTO.getName().equals(dataResource.getName())) {
            checkResName(dataResourceDTO.getName());
        }

        if (ReleaseType.API.getCode() == dataResourceDTO.getReleaseType()) {
            CheckParaUtils.checkStringValidity(dataResourceDTO.getApiAddress(), logger, "API接口地址必填");

            // 校验API接口地址唯一性
            if (!dataResourceDTO.getApiAddress().equals(dataResource.getApiAddress())) {
                checkApiAddress(dataResourceDTO.getApiAddress());
            }
        }

        // sql过滤校验
        if (dataResourceDTO.getType() == ResourceType.TABLE.getCode()) {
            checkSqlFilter(dataResourceDTO);
        }

        List<OrderInfoDto> orderInfoDtoList = dataResourceDTO.getOrderInfoDtoList();
        if (CollectionUtils.isNotEmpty(orderInfoDtoList)) {
            dataResourceDTO.setOrderInfo(JSONObject.toJSONString(orderInfoDtoList));
        }

        // 记录日志
        try {
            BdpLogUtil.log4Update(dataResourceDTO, dataResource);
        } catch (Exception e) {
            logger.error("调用平台服务记录日志异常", e);
        }

        dataResourceDTO.setCreationDate(dataResource.getCreationDate());
        this.updateByPrimaryKeySelective(dataResourceDTO);

        // 新增数据资源标签关联信息
        resourceTagService.deleteByDataResourceId(dataResourceDTO.getId());
        insertResourceTag(dataResourceDTO);
    }

    private void checkSqlFilter(DataResourceDTO dataResourceDTO) {
        if (StringUtils.isEmpty(dataResourceDTO.getSqlFilter())) {
            return;
        }
        String tableId = dataResourceDTO.getTableId();
        if (StringUtils.isNotEmpty(dataResourceDTO.getProjectId())) {
            tableId = dataResourceDao.getTableIdByProjectTableId(tableId);
        }

        BdpTableDTO tableDTO = tableService.selectByPrimaryKey(tableId);
        CheckParaUtils.checkDbObjectValidity(tableDTO, logger, String.format("没有查到数据，请确保id:%s的表数据是否存在", tableId));
        String sql = "select * from " + tableDTO.getName() + " where " + dataResourceDTO.getSqlFilter();
        logger.info("sql过滤 = {}", sql);
        try {
            dataQueryService.getDataListByTable(tableDTO, null, sql, null, 1, 1);
        } catch (Exception e) {
            logger.error("sql过滤验证不通过", e);
            throw e;
        }
    }

    /**
     * 校验API接口地址唯一性
     *
     * @param apiAddress
     */
    private void checkApiAddress(String apiAddress) {
        DataResourceDTO dataResourceQuery = new DataResourceDTO();
        dataResourceQuery.setApiAddress(apiAddress);
        long num = this.selectCount(dataResourceQuery);
        if (num > 0) {
            throw new BusinessException(apiAddress + ",API接口地址已存在");
        }
    }

    /**
     * 校验资源名称唯一性
     *
     * @param name
     */
    private void checkResName(String name) {
        DataResourceDTO dataResourceQuery = new DataResourceDTO();
        dataResourceQuery.setName(name);
        long num = this.selectCount(dataResourceQuery);
        if (num > 0) {
            throw new BusinessException(name + ",资源名称已存在");
        }
    }

    /**
     * 批量新增资源标签关系
     *
     * @param dataResourceDTO
     */
    private void insertResourceTag(DataResourceDTO dataResourceDTO) {
        List<TagDTO> tagList = dataResourceDTO.getTagList();
        List<ResourceTagDTO> resourceTagList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(tagList)) {
            for (TagDTO tag : tagList) {
                ResourceTagDTO resourceTagDTO = new ResourceTagDTO();
                resourceTagDTO.setId(ComUtil.getId());
                resourceTagDTO.setDataResourceId(dataResourceDTO.getId());
                resourceTagDTO.setTagId(tag.getId());
                resourceTagDTO.setCreatedBy(ThreadContextHelper.getUserId() == null ? "1" : ThreadContextHelper.getUserId());
                resourceTagDTO.setCreationDate(new Date());
                resourceTagDTO.setLastUpdateDate(new Date());
                EntityUtils.setCreateAndUpdateInfo(resourceTagDTO);
                resourceTagList.add(resourceTagDTO);
            }
            resourceTagService.insertListByBatch(resourceTagList);
        }
    }

    /**
     * 删除数据资源
     */
    public Boolean deleteDataResource(String ids) {
        CheckParaUtils.checkStringValidity(ids, logger, "没有传入待删除的id");

        String[] idArr = ids.split(Constants.COMMA);
        for (String id : idArr) {
            DataResourceDTO dataResourceDTO = this.selectByPrimaryKey(id);
            CheckParaUtils.checkDbObjectValidity(dataResourceDTO, logger, String.format("没有查到数据，请确保id:%s的资源数据是否存在", id));

            // 已经订阅过的服务，不允许直接删除，给出提示:该服务已经有人订阅，不能删除
            DssSubscribeDTO subscribeDTO = new DssSubscribeDTO();
            subscribeDTO.setDataResourceId(id);
            if (subscribeService.selectCount(subscribeDTO) > 0) {
                throw new BusinessException(dataResourceDTO.getName() + ",该服务已经有人订阅，不能删除");
            }

            // 记录日志
            BdpLogUtil.log4Delete(dataResourceDTO);

            this.deleteByPrimaryKey(dataResourceDTO);
        }
        return true;
    }

    /**
     * 查看数据资源详情
     */
    public DataResourceDTO getDataResourceById(String id) {
        DataResourceDTO dataResource = this.selectByPrimaryKey(id);
        CheckParaUtils.checkDbObjectValidity(dataResource, logger, String.format("没有查到数据，请确保id:%s的资源数据是否存在", id));

        String columnInfo = dataResource.getColumnInfo();
        List<ColumnInfoDto> columnInfoDtoList = new ArrayList<>();
        if (StringUtils.isNotEmpty(columnInfo)) {
            columnInfoDtoList = JSONUtils.toList(columnInfo, ColumnInfoDto.class);
        }
        dataResource.setColumnInfoDtoList(columnInfoDtoList);

        String orderInfo = dataResource.getOrderInfo();
        List<OrderInfoDto> orderInfoDtoList = new ArrayList<>();
        if (StringUtils.isNotEmpty(orderInfo)) {
            orderInfoDtoList = JSONUtils.toList(orderInfo, OrderInfoDto.class);
        }
        dataResource.setOrderInfoDtoList(orderInfoDtoList);

        dataResource.setReleaseTypeString(ReleaseType.getDescByCode(dataResource.getReleaseType()));
        dataResource.setTypeString(ResourceType.getDescByCode(dataResource.getType()));
        dataResource.setStatusString(ResourceStatus.getDescByCode(dataResource.getStatus()));
        dataResource.setTagList(resourceTagService.getTagList(dataResource.getId()));

        if("0".equals(dataResource.getType().toString())) {
            String tableId = dataResource.getTableId();
            if (StringUtils.isNotEmpty(dataResource.getProjectId())) {
                tableId = dataResourceDao.getTableIdByProjectTableId(tableId);
            }
            BdpTableDTO tableDTO = tableService.selectByPrimaryKey(tableId);
            CheckParaUtils.checkDbObjectValidity(tableDTO, logger, String.format("没有查到数据，请确保id:[%s],name:[%s]的表数据是否存在",
                    tableId, dataResource.getTableName()));
            dataResource.setTableName(tableDTO.getName());
        }
        CommonTypeDTO commonTypeDTO = commonTypeService.selectByPrimaryKey(dataResource.getTypeId());
        CheckParaUtils.checkDbObjectValidity(commonTypeDTO, logger, String.format("没有查到数据，请确保id:%s的CommonType是否存在", dataResource.getTypeId()));
        dataResource.setTypeName(commonTypeDTO.getName());

        BdpLogUtil.log4Query(dataResource);
        return dataResource;
    }

    /**
     * 发布/撤回
     */
    public void updateDataResourceStatus(String ids, Integer status) {
        CheckParaUtils.checkStringValidity(ids, logger, "没有传入待发布/撤回的ID");

        String[] idArr = ids.split(Constants.COMMA);
        for (String id : idArr) {
            DataResourceDTO dataResourceDTO = this.selectByPrimaryKey(id);
            CheckParaUtils.checkDbObjectValidity(dataResourceDTO, logger, String.format("没有查到数据，请确保id:%s的资源数据是否存在", id));

            // 修改状态
            dataResourceDTO.setStatus(status);
            this.updateByPrimaryKeySelective(dataResourceDTO);
            //记录日志
            String logTitle = "";
            if(status == 1){
                logTitle = "资源发布：【";
            }else if(status == 2){
                logTitle = "资源撤回：【";
            }
            logTitle += dataResourceDTO.getName()+"】";
            BdpLogUtil.log("数据服务模块",logTitle, PlatformConstant.OpType.update);
        }
    }

    /**
     * 数据预览
     *
     * @return
     */
    public Map<String, Object> preview(String id, String subscribeId, Integer currentPage, Integer pageSize) throws Exception {
        Map<String, Object> map = new HashMap<>(8);
        DataResourceDTO dataResourceDTO = this.selectByPrimaryKey(id);
        CheckParaUtils.checkDbObjectValidity(dataResourceDTO, logger, String.format("没有查到数据，请确保id:%s的资源数据是否存在", id));

        try {
            if (dataResourceDTO.getReleaseType() == ReleaseType.DATA.getCode()) {
                if (dataResourceDTO.getType() == ResourceType.TABLE.getCode()) {
                    map = getDataListFromDB(id, currentPage, pageSize, null);
                } else {
                    map = getFileInfo(dataResourceDTO.getTableId());
                }
            } else {
                if (dataResourceDTO.getType() == ResourceType.TABLE.getCode()) {
                    map = getApiInfo(dataResourceDTO, subscribeId);
                } else {
                    map = getFileInfo(dataResourceDTO.getTableId());
                }
            }
        } catch (Exception e) {
            logger.error("数据预览异常", e);
            throw e;
        }

        String logTitle = "查看数据预览：【" + dataResourceDTO.getName() + "】";
        BdpLogUtil.log("服务管理模块", logTitle, PlatformConstant.OpType.select);
        return map;
    }

    /**
     * 获取文件信息
     *
     * @param resourceId
     * @return
     */
    public Map<String, Object> getFileInfo(String resourceId) {
        Map<String, Object> map = new HashMap<>(8);
        String filePath = dataResourceDao.getFilePathFromResource(resourceId);
        map.put("filePath", filePath);
        return map;
    }

    /**
     * 从数据库实时查询数据
     *
     * @return 查询数据
     */
    public Map<String, Object> getDataListFromDB(String id, Integer currentPage, Integer pageSize, Map<String, Object> parameterMap) {
        Map<String, Object> map = new HashMap<>(8);
        DataResourceDTO dataResourceDTO = this.selectByPrimaryKey(id);
        CheckParaUtils.checkDbObjectValidity(dataResourceDTO, logger, String.format("没有查到数据，请确保id:%s的资源数据是否存在", id));

        String tableId = dataResourceDTO.getTableId();
        if (StringUtils.isNotEmpty(dataResourceDTO.getProjectId())) {
            tableId = dataResourceDao.getTableIdByProjectTableId(tableId);
        }

        BdpTableDTO tableDTO = tableService.selectByPrimaryKey(tableId);
        CheckParaUtils.checkDbObjectValidity(tableDTO, logger, String.format("没有查到数据，请确保id:[%s],name:[%s]的表数据是否存在",
                tableId, dataResourceDTO.getTableName()));

        List<ColumnInfoDto> columnInfoDtoList = JSONUtils.toList(dataResourceDTO.getColumnInfo(), ColumnInfoDto.class);
        // 无字段直接返回
        if (CollectionUtils.isEmpty(columnInfoDtoList)) {
            return map;
        }

        for (ColumnInfoDto columnInfo : columnInfoDtoList) {
            columnInfo.setName(columnInfo.getName().toLowerCase());
        }

        String sql = buildSqlFromDataResource(dataResourceDTO, tableDTO, columnInfoDtoList, parameterMap);
        logger.info("sql = {}", sql);

        map = dataQueryService.getDataListByTable(tableDTO, null, sql, parameterMap, currentPage, pageSize);
        map.put("dataResource", dataResourceDTO);
        map.put("columnList", columnInfoDtoList);
        map.remove("modelInfo");
        return map;
    }

    /**
     * 获取API信息
     *
     * @param dataResourceDTO dataResourceDTO
     * @return API信息
     */
    public Map<String, Object> getApiInfo(DataResourceDTO dataResourceDTO, String subscribeId) {
        Map<String, Object> map = new HashMap<>(8);
        List<ApiParamDto> paramList = new ArrayList<>();

        // get请求带分页参数
        if (HttpMethod.GET.name().equalsIgnoreCase(dataResourceDTO.getRequestMethod())) {
            ApiParamDto currentPage = new ApiParamDto();
            currentPage.setName("pageNo");
            currentPage.setCnName("当前页");
            currentPage.setRequired(1);
            currentPage.setExample("1");
            paramList.add(currentPage);
            ApiParamDto pageSize = new ApiParamDto();
            pageSize.setName("pageSize");
            pageSize.setCnName("每页大小");
            pageSize.setRequired(1);
            pageSize.setExample("10");
            paramList.add(pageSize);
        }

        List<JSONObject> columnInfoList = new ArrayList<>();
        List<ColumnInfoDto> columnInfoDtoList = JSONUtils.toList(dataResourceDTO.getColumnInfo(), ColumnInfoDto.class);
        if (CollectionUtils.isNotEmpty(columnInfoDtoList)) {
            for (ColumnInfoDto columnInfo : columnInfoDtoList) {
                if (columnInfo.getParam() == 1) {
                    ApiParamDto param = new ApiParamDto();
                    param.setName(columnInfo.getName());
                    param.setCnName(columnInfo.getCnName());
                    param.setRequired(0);
                    param.setExample("");
                    paramList.add(param);
                }

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("columnName", columnInfo.getName());
                jsonObject.put("description", columnInfo.getCnName());
                jsonObject.put("type", columnInfo.getType());
                columnInfoList.add(jsonObject);
            }
        }

        dataResourceDTO.setApiAddress(Constants.PUBLISH_DATA_SERVICE_URL_PREFIX + dataResourceDTO.getApiAddress());
        map.put("dataResource", dataResourceDTO);
        map.put("paramList", paramList);
        map.put("token", dataResourceDao.getToken(dataResourceDTO.getId(), subscribeId));
        buildResponseData(dataResourceDTO.getRequestMethod(), map, columnInfoList);
        return map;
    }

    /**
     * 构造响应数据
     * @param requestMethod
     * @param map
     * @param columnInfoList
     */
    public void buildResponseData(String requestMethod, Map<String, Object> map, List<JSONObject> columnInfoList) {
        JSONObject responseData = new JSONObject();

        JSONObject message = new JSONObject();
        message.put("description", "返回信息");
        responseData.put("message", message);

        JSONObject errorDesc = new JSONObject();
        errorDesc.put("description", "错误信息");
        responseData.put("errorDesc", errorDesc);

        JSONObject retCode = new JSONObject();
        retCode.put("description", "返回码");
        responseData.put("retCode", retCode);

        JSONObject responseBody = new JSONObject();
        responseBody.put("description", "返回结果");
        responseBody.put("type","object");
        if (HttpMethod.GET.name().equals(requestMethod)) {
            JSONObject result = new JSONObject();
            result.put("items", columnInfoList);
            result.put("description", "数据");
            responseBody.put("result", result);

            // 分页信息
            JSONObject pageParameter = new JSONObject();
            pageParameter.put("description", "翻页参数");
            pageParameter.put("type","object");
            responseBody.put("pageParameter", pageParameter);

            JSONObject rows = new JSONObject();
            rows.put("description", "每页行数");
            rows.put("type", "number");
            pageParameter.put("rows", rows);

            JSONObject page = new JSONObject();
            page.put("description", "当前页数");
            page.put("type", "number");
            pageParameter.put("page", page);

            JSONObject totalPage = new JSONObject();
            totalPage.put("description", "总页数");
            totalPage.put("type", "number");
            pageParameter.put("totalPage", totalPage);

            JSONObject totalCount = new JSONObject();
            totalCount.put("description", "总记录数");
            totalCount.put("type", "number");
            pageParameter.put("totalCount", totalCount);

        }
        responseData.put("responseBody", responseBody);
        map.put("responseData", responseData);
    }

    /**
     * 组装查询sql语句
     *
     * @param dataResourceDTO   数据资源DTO
     * @param tableDTO          数据模型DTO
     * @param columnInfoDtoList 模型列信息
     * @return 组装sql语句
     */
    private String buildSqlFromDataResource(DataResourceDTO dataResourceDTO,
                                            BdpTableDTO tableDTO,
                                            List<ColumnInfoDto> columnInfoDtoList,
                                            Map<String, Object> parameterMap) {
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("select ");

        int i = 1;
        for (ColumnInfoDto columnInfo : columnInfoDtoList) {
            sqlBuilder.append(columnInfo.getName());
            if (i < columnInfoDtoList.size()) {
                sqlBuilder.append(",");
            }
            i++;
        }

        sqlBuilder.append(" from ").append(tableDTO.getName());

        if (StringUtils.isNotEmpty(dataResourceDTO.getSqlFilter())) {
            sqlBuilder.append(" where ").append(dataResourceDTO.getSqlFilter());
        }

        if (MapUtils.isNotEmpty(parameterMap)) {
            if (!sqlBuilder.toString().contains("where")) {
                sqlBuilder.append(" where 1 =1 ");
            }

            for (ColumnInfoDto columnInfoDto : columnInfoDtoList) {
                if (columnInfoDto.getParam() == 1 && parameterMap.containsKey(columnInfoDto.getName())) {
                    sqlBuilder.append(" and ").append(columnInfoDto.getName()).append(" ").append(MapUtils.getString(parameterMap, columnInfoDto.getName()));
                }
            }
        }

        List<OrderInfoDto> orderInfoDtoList = JSONUtils.toList(dataResourceDTO.getOrderInfo(), OrderInfoDto.class);
        if (CollectionUtils.isNotEmpty(orderInfoDtoList)) {
            int j = 1;
            sqlBuilder.append(" order by ");
            for (OrderInfoDto orderInfo : orderInfoDtoList) {
                sqlBuilder.append(orderInfo.getName());
                // 排序方式 升序：1，降序：0
                if (orderInfo.getOrder() == 1) {
                    sqlBuilder.append(" asc ");
                } else {
                    sqlBuilder.append(" desc ");
                }

                if (j < orderInfoDtoList.size()) {
                    sqlBuilder.append(",");
                }
                j++;
            }
        }

        return sqlBuilder.toString();
    }

    /**
     * CSV数据下载
     */
    public void downloadDataFromDBToCsv(String id, String userId, String type, HttpServletResponse response) throws Exception {
        List<Object[]> cellList = new ArrayList<>();
        String fileName = "数据预览.csv";
        Map<String, String> userMap = new HashMap<>();

        // 记录下载日志
        DssLogDTO logDTO = new DssLogDTO();
        logDTO.setId(ComUtil.getId());
        logDTO.setDataResourceId(id);
        logDTO.setType(LogRecordCode.DOWNLOAD.getCode());
        logDTO.setStartTime(new Date());
        logDTO.setCallUserId(userId);
        //用户名称不保存
//        Map<String, Set<String>> convertFormData = new HashMap<>();
//        try {
//            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, userId);
//            if (convertFormData.size() > 0) {
//                //获取请求结果
//                Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
//                String name = BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, userId);
//                logDTO.setCallUserName(name);
//            }
//        } catch (Exception e) {
//            logger.error("根据用户ID调用平台服务返回用户名称异常,", e);
//        }


        try {
            int pageSize = 10;
            // TODO 下载数据量Integer.MAX_VALUE
            // 预览界面下载10条数据，数据详情界面下载全部数据
            if (StringUtils.isNotEmpty(type) && "detail".equals(type)) {
                pageSize = Integer.MAX_VALUE;
            }

            Map<String, Object> map = getDataListFromDB(id, 1, pageSize, null);
            List<ColumnInfoDto> columnInfoDtoList = (List<ColumnInfoDto>) map.get("columnList");
            if (CollectionUtils.isEmpty(columnInfoDtoList)) {
                return;
            }

            String[] tableHeaderArr = new String[columnInfoDtoList.size()];
            int i = 0;
            for (ColumnInfoDto columnInfo : columnInfoDtoList) {
                tableHeaderArr[i] = columnInfo.getName();
                i++;
            }

            List<Map<String, Object>> resultList = (List<Map<String, Object>>) map.get("resultList");
            if (CollectionUtils.isNotEmpty(resultList)) {
                List<Object> mapValuesList;
                Object[] obj;

                for (Map<String, Object> dataMap : resultList) {
                    mapValuesList = new ArrayList<>(dataMap.size());
                    for (ColumnInfoDto columnInfo : columnInfoDtoList) {
                        mapValuesList.add(dataMap.get(columnInfo.getName()));
                    }

                    obj = mapValuesList.toArray();
                    cellList.add(obj);
                }
            }

            String logTitle = "下载数据【" + resultList.size() + "】条";
            BdpLogUtil.log("服务管理模块", logTitle, PlatformConstant.OpType.select);
            logger.info("下载数据" + resultList.size() + "条");

            byte[] bytes = ExportCSVUtil.writeCsvAfterToBytes(tableHeaderArr, cellList);
            ExportCSVUtil.downLoadCsv(fileName, bytes, response);

            logDTO.setCallStatus(1);
            logDTO.setCallResult("下载数据" + resultList.size() + "条");
        } catch (Exception e) {
            logDTO.setCallStatus(0);
            logDTO.setCallResult(e.getMessage());
            logger.error("下载数据异常", e);
            throw e;
        }

        logDTO.setEndTime(new Date());
        logService.insert(logDTO);
    }

    /**
     * 从文件系统下载文件
     *
     * @param id              资源ID
     * @param dataResourceDTO 资源DTO
     * @param request         request
     * @param response        response
     */
    public void downloadFileFromFileSystem(String id,
                                           DataResourceDTO dataResourceDTO,
                                           HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {
        if (dataResourceDTO == null) {
            dataResourceDTO = this.selectByPrimaryKey(id);
        }

        CheckParaUtils.checkDbObjectValidity(dataResourceDTO, logger, String.format("没有查到数据，请确保id:%s的资源数据是否存在", id));

        String filePath = dataResourceDao.getFilePathFromResource(dataResourceDTO.getTableId());
        CheckParaUtils.checkStringValidity(filePath, logger, String.format("没有查到数据，请确保id:%s的文件数据是否存在", dataResourceDTO.getTableId()));

        hdfsFileOperateService.downloadFile(filePath, request, response);
    }

    /**
     * 获取模型分类及模型
     * 注意：
     *  1、数据开发工作台-数据发布，新增服务资源时获取项目模型（传入projectId）；
     *  2、数据服务，新增服务资源时获取公共模型（不传入projectId），并根据登录用户角色过滤模型分类及模型
     * @param projectId
     * @return
     * @throws Exception
     */
    public List<CommonTableDto> getTableTree(String projectId) throws Exception {
        List<CommonTableDto> result = null;
        if (StringUtils.isNotEmpty(projectId)) {
            // 数据开发工作台-数据发布，新增服务资源时获取项目模型（传入projectId）；
            result = this.getCommonTypeAndTableList(CommonTypeEnums.DATATABLE, projectId);
        } else {
            //数据服务，新增服务资源时获取公共模型（不传入projectId），并根据登录用户角色过滤模型分类及模型
            result = this.getCategoryAndTableList();
        }

        return result;
    }

    /**
     * 查询数据空间中的表管理树
     *
     * @param type
     * @param projectId
     * @return
     */
    public List<CommonTableDto> getCommonTypeAndTableList(String type, String projectId) {
        try {
            // 顶级节点
            List<CommonTableDto> result = new ArrayList<>();
            // 子节点数据
            Map<String, List<CommonTableDto>> map = new HashMap<>();
            List<CommonTypeDTO> commonTypeList = new ArrayList<>();

            // 项目空间通用树
            if (StringUtils.isNotEmpty(projectId)) {
                List<CommonTypeDTO> topType = commonTypeService.selectByTypeAndParentId(type,"-1");
                CommonTypeDTO commonTypeDTO = new CommonTypeDTO();
                commonTypeDTO.setType(type);
                commonTypeDTO.setProjectId(projectId);
                List<CommonTypeDTO> childrenType = commonTypeService.selectList(commonTypeDTO);
                commonTypeList = Stream.of(topType, childrenType)
                        .flatMap(Collection::stream)
                        .distinct()
                        .sorted(Comparator.comparing(CommonTypeDTO::getOrderBy, Comparator.nullsLast(Integer::compareTo)))
                        .collect(Collectors.toList());
            }

            String rootTypeId = "";
            if (CollectionUtils.isNotEmpty(commonTypeList)) {
                for (CommonTypeDTO commonType : commonTypeList) {
                    CommonTableDto commonTable = new CommonTableDto();
                    BeanUtils.copyProperties(commonTable, commonType);

                    if ("-1".equals(commonType.getParentId())) {
                        result.add(commonTable);
                        rootTypeId = commonType.getId();
                    } else {
                        if (map.containsKey(commonType.getParentId())) {
                            map.get(commonType.getParentId()).add(commonTable);
                        } else {
                            List<CommonTableDto> commonTableList = new ArrayList<>();
                            commonTableList.add(commonTable);
                            map.put(commonType.getParentId(), commonTableList);
                        }
                    }
                }
            }

            List<BdpTableDTO> tableList = tableService.getTableList(rootTypeId, projectId);
            buildChildren(result, map, projectId, tableList);

            // 顶级节点不必返回
            if (result.size() == 1) {
                result = result.get(0).getChildren();
            }
            return result;
        } catch (Exception e) {
            logger.error("查询数据空间中的表管理树异常", e);
            throw new BusinessException(e.getMessage(), e);
        }
    }

    private void buildChildren(List<CommonTableDto> list, Map<String, List<CommonTableDto>> map, String projectId, List<BdpTableDTO> tableList) {
        for (CommonTableDto commonTable : list) {
            List<CommonTableDto> commonTableList = map.get(commonTable.getId());
            if (CollectionUtils.isNotEmpty(commonTableList)) {
                buildChildren(commonTableList, map, projectId, tableList);
                commonTable.setChildren(commonTableList);
            } else {
                List<CommonTableDto> commonTableDtoList = new ArrayList<>();
                // 叶子节点增加表数据到树
                if (CollectionUtils.isNotEmpty(tableList)) {
                    for (BdpTableDTO tableDTO : tableList) {
                        if (commonTable.getId().equals(tableDTO.getTypeId())) {
                            CommonTableDto commonTableDto = new CommonTableDto();
                            commonTableDto.setId(tableDTO.getId());
                            commonTableDto.setName(tableDTO.getName());
                            commonTableDto.setTableFlag(1);
                            commonTableDtoList.add(commonTableDto);
                        }
                    }
                }

                commonTable.setChildren(commonTableDtoList);
            }
        }
    }

    /**
     * 获取模型分类及模型
     * 注意：
     *  1、数据服务，新增服务资源时获取公共模型(仅关注是否具有查看权限)
     * @return
     * @throws Exception
     */
    public List<CommonTableDto> getCategoryAndTableList() {
        // 根据登录用户角色，获取模型分类树
        List<BdpDasCategoryDTO> categoryTree = categoryService.findCategoryList();

        // 根据登录用户角色，获取模型列表
        List<String> roleIdList = getRoleListByUserId(ThreadContextHelper.getUserId());
        List<CommonTableDto> tableList = getTableListByRole(roleIdList);
        Map<String, List<CommonTableDto>> typeTableMap = getTypeTableMap(tableList);

        // 构建分类树和表结构
        List<CommonTableDto> result = recursiveSetTable(categoryTree, typeTableMap);

        // 顶级节点不必返回
        if (result.size() == 1) {
            result = result.get(0).getChildren();
        }
        return result;
    }

    /**
     * 根据表ID查询列
     * 空间tableId存bdp_dds_r_project_table表id
     * 公共tableId存table表id
     *
     * @param tableId
     * @throws Exception
     */
    public List<BdpColumnDTO> getColumnListByTableId(String tableId) throws Exception {
        BdpTableDTO tableDTO = tableService.selectByPrimaryKey(tableId);
        if (tableDTO == null) {
            tableId = dataResourceDao.getTableIdByProjectTableId(tableId);
        }

        if (StringUtils.isEmpty(tableId)) {
            return null;
        }

        BdpColumnDTO columnDTO = new BdpColumnDTO();
        columnDTO.setTableId(tableId);
        List<BdpColumnDTO> columnList = columnService.selectList(columnDTO)
                .stream().sorted(Comparator.comparing(BdpColumnDTO::getOrderBy))
                .collect(Collectors.toList());

        return columnList;
    }

    /**
     * 获取文件目录树
     *
     * @param projectId
     * @return
     */
    public List<ResourceDTO> getResourceTree(String projectId) {
        try {
            // 顶级节点
            List<ResourceDTO> result = new ArrayList<>();
            // 子节点数据
            Map<String, List<ResourceDTO>> map = new HashMap<>();
            // 记录日志
            ResourceDTO resource = new ResourceDTO();
            resource.setPid("-1");
            List<ResourceDTO> topResources = resourceService.selectList(resource);

            ResourceDTO resourceDTO = new ResourceDTO();
            resourceDTO.setProjectId(projectId);
            resourceDTO.setType(ResourceDTO.TYPE_RESOURCE);
            resourceDTO.setDirectory(ResourceDTO.DIRECTORY_FOLDER);

            List<ResourceDTO> childrenResources = resourceService.selectList(resourceDTO);
            List<ResourceDTO> resourceList = Stream.of(topResources, childrenResources)
                    .flatMap(Collection::stream)
                    .distinct()
                    .sorted(Comparator.comparing(ResourceDTO::getCreationDate).reversed())
                    .collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(resourceList)) {
                for (ResourceDTO resources : resourceList) {
                    if ("-1".equals(resources.getPid())) {
                        result.add(resources);
                    } else {
                        if (map.containsKey(resources.getPid())) {
                            List<ResourceDTO> resourceDtoList = map.get(resources.getPid());
                            resourceDtoList.add(resources);
                        } else {
                            List<ResourceDTO> resourcesDTOList = new ArrayList<>();
                            resourcesDTOList.add(resources);
                            map.put(resources.getPid(), resourcesDTOList);
                        }
                    }
                }
            }

            List<ResourceDTO> resList = dataResourceDao.getFileList(projectId);
            buildChildDirectoryAndFile(result, map, projectId, resList);
            return result;
        } catch (Exception e) {
            logger.error("获取文件目录树异常", e);
            throw new BusinessException(e.getMessage(), e);
        }
    }

    private void buildChildDirectoryAndFile(List<ResourceDTO> list, Map<String, List<ResourceDTO>> map, String projectId, List<ResourceDTO> resList) {
        for (ResourceDTO resource : list) {
            List<ResourceDTO> resourceList = map.get(resource.getId());

            List<ResourceDTO> childResourceList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(resList)) {
                for (ResourceDTO resourceDTO : resList) {
                    if (resourceDTO.getPid().equals(resource.getId())) {
                        resourceDTO.setDirectory(0);
                        resourceDTO.setName(resourceDTO.getName() + "." + resourceDTO.getFileSuffix());
                        childResourceList.add(resourceDTO);
                    }
                }
            }

            if (CollectionUtils.isNotEmpty(resourceList)) {
                buildChildDirectoryAndFile(resourceList, map, projectId, resList);
                resourceList.addAll(childResourceList);
                resource.setChildren(resourceList);
            } else {
                resource.setChildren(childResourceList);
            }
        }
    }

    /**
     * 根据角色获取模型表
     * @param roleIdList
     * @return
     */
    private List<CommonTableDto> getTableListByRole(List<String> roleIdList) {
        List<CommonTableDto> tableList = new ArrayList<>();
        if (CollectionUtils.isEmpty(roleIdList)) {
            return tableList;
        }

        // 根据角色查询模型表，并转换为CommonTableDto结构
        Page<BdpTableDTO> tableQueryRet = tableService.qureyTableListWithPerm(roleIdList,
                TableTypeEnum.TABLE_PHYSICAL.getCode(), "0", null, StatusEnums.RUNNING.getCode()
                , null,
                null,
                null,
                null);
        if (CollectionUtils.isNotEmpty(tableQueryRet.getResult())) {
            for (BdpTableDTO dasTableDTO : tableQueryRet.getResult()) {
                if (dasTableDTO == null || StringUtils.isEmpty(dasTableDTO.getId()) || StringUtils.isEmpty(dasTableDTO.getTypeId())) {
                    continue;
                }

                CommonTableDto tableDto = new CommonTableDto();
                tableDto.setId(dasTableDTO.getId());
                tableDto.setParentId(dasTableDTO.getTypeId());
                tableDto.setName(dasTableDTO.getName());
                tableDto.setTableFlag(1);
                tableDto.setLeaf(1);
                tableList.add(tableDto);
            }
        }

        return tableList;
    }

    /**
     * 获取Map<模型分类ID，模型列表>
     * @param tableList
     * @return
     */
    private Map<String, List<CommonTableDto>> getTypeTableMap(List<CommonTableDto> tableList) {
        if (CollectionUtils.isEmpty(tableList)) {
            return new HashMap<>();
        }

        Map<String, List<CommonTableDto>> allTblMap = new HashMap<>();
        for (CommonTableDto dto : tableList) {
            if (dto == null || StringUtils.isEmpty(dto.getId()) || StringUtils.isEmpty(dto.getParentId())) {
                continue;
            }

            if (!allTblMap.containsKey(dto.getParentId())) {
                List<CommonTableDto> child = new ArrayList<>();
                child.add(dto);
                allTblMap.put(dto.getParentId(), child);
                continue;
            }

            List<CommonTableDto> child = allTblMap.get(dto.getParentId());
            child.add(dto);
        }

        return allTblMap;
    }

    /**
     * 递归构建模型分类树和表结构
     * @param categoryTree 模型分类树（属性结构）
     * @param allTblMap 获取Map<模型分类ID，模型列表>
     */
    private List<CommonTableDto> recursiveSetTable(List<BdpDasCategoryDTO> categoryTree, Map<String, List<CommonTableDto>> allTblMap) {
        List<CommonTableDto> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(categoryTree)) {
            return result;
        }
        if (allTblMap == null || allTblMap.size() <= 0) {
            return result;
        }

        for (BdpDasCategoryDTO category : categoryTree) {
            if (category == null) {
                continue;
            }

            CommonTableDto commonTable = new CommonTableDto();
            try {
                BeanUtils.copyProperties(commonTable, category);
            } catch (Exception e) {
                logger.error("查询公共表管理树异常", e);
                throw new BusinessException(e.getMessage(), e);
            }
            result.add(commonTable);

            if (CollectionUtils.isNotEmpty(category.getChildren())) {
                commonTable.setChildren(recursiveSetTable(category.getChildren(), allTblMap));
            }

            // 只有叶子节点下才有模型表
            if (category.getLeaf() == 1) {
                commonTable.setChildren(allTblMap.get(category.getId()));
            }
        }

        return result;
    }

    /**
     * 根据用户ID获取角色列表
     * @param loginUserId
     * @return
     */
    private List<String> getRoleListByUserId(String loginUserId) {
        if (StringUtils.isEmpty(loginUserId)) {
            return new ArrayList<>();
        }

        List<SysRole> sysRoleList = this.sysUserRoleClient.getSysRoleListBySysUserIdNoAppId(loginUserId);
        if (CollectionUtils.isNotEmpty(sysRoleList)) {
            return sysRoleList.stream().map(item -> item.getId()).collect(Collectors.toList());
        }

        return new ArrayList<>();
    }

    /**
     * 查询服务目录列表
     */
    public QueryRespBean<DataResourceDTO> getServiceCatalogList(String typeId,
                                                                String name,
                                                                String viewSort,
                                                                Integer pageNo,
                                                                Integer pageSize) throws Exception {
        List<String> typeIdList = new ArrayList<>();
        if (StringUtils.isNotEmpty(typeId)) {
            commonTypeService.typeIdConvert(typeId, typeIdList, "dataServiceType");
        }

        QueryRespBean<DataResourceDTO> queryRespBean = new QueryRespBean<>();
        List<String> wordSecretList = ThreadContextHelper.getWordSecretList();
        com.github.pagehelper.PageHelper.startPage(pageNo, pageSize);
        Page<DataResourceDTO> dataResourceList = dataResourceDao.getServiceCatalogList(typeIdList, name, viewSort, wordSecretList);
        // 追加审核状态
        appendAuditStatus(dataResourceList);

        valueConvert(dataResourceList);
        queryRespBean.setResult(dataResourceList);
        BdpLogUtil.log4Query(queryRespBean);
        return queryRespBean;
    }

    /**
     * 追加审核状态
     * @param dataResourceList
     */
    private void appendAuditStatus(List<DataResourceDTO> dataResourceList) {
        if (CollectionUtils.isEmpty(dataResourceList)) {
            return;
        }
        List<String> dataResourceIdList = dataResourceList.stream().map(DataResourceDTO::getId).collect(Collectors.toList());
        List<DssSubscribeDTO> subscribeList = subscribeService.getSubscribeList(dataResourceIdList);
        if (CollectionUtils.isEmpty(subscribeList)) {
            return;
        }
        String userId = ThreadContextHelper.getUserId();
        for(DataResourceDTO res : dataResourceList){
            List<DssSubscribeDTO> subList = subscribeList.stream().filter(
                    subscribe -> subscribe.getDataResourceId().equals(res.getId())
                            && subscribe.getUserId().equals(userId)).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(subList)) {
                res.setAuditStatus(subList.get(0).getAuditStatus());
            }
        }
    }

    /**
     * 更新查看次数
     */
    public void addViewCount(DataResourceDTO dataResourceDTO) {
        if (StringUtils.isBlank(dataResourceDTO.getId())) {
            throw new BusinessException("id为空！");
        }

        DataResourceDTO old = this.selectByPrimaryKey(dataResourceDTO.getId());
        Long oldCount = old.getViewCount();
        if(oldCount == null){
            oldCount = 0L;
        }
        old.setViewCount(oldCount + 1);
        this.updateByPrimaryKeySelective(old);
    }

}
